package jzqb.annotation.PermissionCheck;

import haha.life.normal.TokenUtils;
import jzqb.common.Result;
import jzqb.dao.AdminPermissionDao;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class PermissionCheckAspect {

    @Autowired AdminPermissionDao adminPermissionDao;

    //定义切点
    @Pointcut("@annotation(jzqb.annotation.PermissionCheck.PermissionCheck)")//注意这个写类的全路径
    public void permissionCheckPoint(){

    }

    @Before("permissionCheckPoint()")
    public void beforePoint(JoinPoint joinPoint){

    }

    //切点后执行
    @After("permissionCheckPoint()")
    public void afterPoint(){

    }

    @Around("permissionCheckPoint()")
    public Object  around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("around process...");
        //获取token
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = req.getHeader("token");
        System.out.println(token);
        //解析token获取id
        String userID =  TokenUtils.checkTokenReturnID(token);

        System.out.println("登录人是:" + userID);
        if (userID == null){
            return Result.fail("token错误或过期,请重新登录");
        }

        MethodSignature signature = (MethodSignature) pjp.getSignature();//从切面织入点处，通过反射机制获取织入点处的方法
        Method method = signature.getMethod();//获取切入点所在的方法
        PermissionCheck permissionCheckClass = method.getAnnotation(PermissionCheck.class);//获取注解内容
        String[] aquirePermissionList = permissionCheckClass.permissionTypeList();
//        String type = permissionCheckClass.permissionType();

        boolean pass = adminPermissionDao.permissionCheck(userID,aquirePermissionList);
        if (pass){
            return pjp.proceed();
        }else {
            return Result.fail("抱歉!权限不足");
        }
    }

    //切面
    @AfterReturning("permissionCheckPoint()")
    public void saveLog(JoinPoint joinPoint){
//        System.out.println("-----------记录日志---------");
    }

}
